import { useCallback } from "react";
import { useSelector, useDispatch } from "react-redux"
import Creators from "../store/actions"
// 拿到抢购的api
import usersApi from "../api/users"
export const useUsers = () => {
  const users = useSelector(state => state.users_list)
  const { curPage, eachPage, rows, total, maxPage, Address } = users
  const dispatch = useDispatch()

  // 发送请求获取数据
  const getUsers = useCallback(
    async () => {
      const data = await usersApi.getlist({ curPage, eachPage })
      dispatch(Creators.usersGetUsers({ data }))
    }, [curPage, eachPage])

  // 修改页码
  const choseUserCurpage = (setcurpage) => {
    dispatch(Creators.usersSetCurpage({ setcurpage }))
  }

  // 修改每页显示条数
  const choseUserEachpage = (seteachpage) => {

    dispatch(Creators.usersSetEachpage({ seteachpage }))
  }

  const updataHome = useCallback(async ({ _id, home }) => {
    const result = await usersApi.updataHome({ _id, home })

    const data = await usersApi.getlist({ curPage, eachPage })
    dispatch(Creators.usersGetUsers({ data }))
    return result

  }, [dispatch])


  // 删除一个地址
  const delOneAddress = useCallback(async (info) => {
    const { _id, addressId } = info
    const result = await usersApi.deleOneaddress({ _id, addressId })
    const data = await usersApi.getlist({ curPage, eachPage })
    dispatch(Creators.usersGetUsers({ data }))
    return result

  }, [dispatch])

  // 按用户名 查询用户
  const selectTosever = useCallback(async (data1) => {
    const data = {}
    data.rows = await usersApi.selectfromName(data1)
    dispatch(Creators.usersGetUsers({ data }))

    return data

  }, [dispatch])

  return [{ rows, curPage, eachPage, total, maxPage, Address }, { getUsers, choseUserCurpage, choseUserEachpage, updataHome, delOneAddress, selectTosever }]


}